import loadingCpt from '@/components/pageLoading';
import { core as udp } from '@cscec/udp-core';
import { IObject, registerComponent, setGlobalConfig, setUmiHooks } from '@cscec/udp-mobile-ui';
import {
  connect,
  getDvaApp,
  history,
  Navigate,
  Outlet,
  useDispatch,
  useModel,
  useSelector,
  useStore
} from '@umijs/max';
import React from 'react';
import routeConfig from '../route';
import AuthRoute from './components/AuthRoute';
import VConsole from'vconsole';
registerComponent({
  
}, { isHelp: true });

//#endregion

setUmiHooks(() => ({ connect, useDispatch, useStore, useSelector, getDvaApp, history, useModel }));


//const vonsole =new VConsole()
/**
 * 动态加载页面组件
 * webpackExclude不要删除，该配置可以屏蔽加载多余的依赖，
 * 详情可以参考： https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import
 * @param path 组件路径
 */
function loadComponent(path: string) {
  const realPath = path.replace('@', '');

  return React.lazy(
    () =>
      import(
        /* webpackExclude: /(\.*\model\.tsx)|(\.*\.(ts|ejs|js|json|css|less|scss))$/, webpackChunkName:'pages/[request]' */
        `@/pages/${realPath}`
      )
  );
}

const cacheTitle: any = {};

/**
 * 格式化路由
 * @param menus 路由数组
 */
function parseRoute(menus: any[], { title = '' }: { title?: string } = {}) {
  const newRoutes: any = [];
  menus.forEach(
    (menu: { microApp?: any; path?: any; component?: any; children?: any; routes?: any; name?: any; query?: any }) => {
      const { path, component, children, routes, name, query } = menu;
      const currentTitle = title || name || cacheTitle[path];
      if (path && currentTitle) {
        cacheTitle[path.replace('/list', '/detail')] = currentTitle;
      }
      const routeChild = children || routes;
      const hasChildren = !!routeChild?.length;
      if (component) {
        const route: any = {
          exact: true,
          title: currentTitle,
          path: path || (hasChildren ? `/${routeChild[0].path?.match(/\/(.+?)\//)?.[1] || ''}` : '/'),
          query,
          element: (
            //这里组件帮助跳回登录页
             <AuthRoute>
            <React.Suspense fallback={loadingCpt({})}>
              {React.createElement(loadComponent(component), { children: hasChildren ? <Outlet /> : null })}
            </React.Suspense>
            </AuthRoute>
          )
        };
        if (hasChildren) {
          route.children = parseRoute(routeChild, { title: currentTitle });
          route.exact = false;
        }
        newRoutes.push(route);
      } else if (hasChildren) {
        Array.prototype.push.apply(newRoutes, parseRoute(routeChild, { title: currentTitle }));
      } else if (menu.microApp) {
        newRoutes.push(menu);
      }
    }
  );
  newRoutes.length > 0 && newRoutes.push({ path: '', element: <Navigate to={newRoutes[0].path} replace /> });
  return newRoutes;
}

/**
 * 动态修改路由
 * @param routes 默认路由
 */
export function patchClientRoutes({ routes }: IObject) {
  const childRoutes = parseRoute(routeConfig, { title: '' });
  const routeLen = routes.length;
  if (routeLen > 0) {
    routes[routeLen - 1].children = childRoutes;
  } else {
    Array.prototype.push.apply(routes, childRoutes);
  }
}

export const qiankun = {
  mount(props: any) {
    const masterInfo = props?.getMasterInfo?.();
    if (!masterInfo) return;
    udp.setUser(masterInfo.getUser());
    udp.registerExternal({
      getMasterObserver() {
        return masterInfo.getObserver?.();
      }
    }, true);
    // 兼容平台API
    if (masterInfo.PlatformAPI) udp.registerExternal({ PlatformAPI: masterInfo.PlatformAPI }, true);
  }
};
